package com.ny.dao.impl;

import com.ny.entity.Stud;
import com.ny.dao.StudentDao;
import com.ny.until.Sqlconnect;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class StudentDaoImpl implements StudentDao {
    Connection cont = Sqlconnect.getCont();

    public StudentDaoImpl() throws SQLException, ClassNotFoundException {
    }



    @Override
    public int addStu(Stud stud) throws SQLException {
        String sql = "insert into students(name,phone,password) values(?,?,?)";
        PreparedStatement pst = cont.prepareStatement(sql);

        pst.setString(1,stud.getStuName());
        pst.setString(2,stud.getStuPwd());
        pst.setString(3,stud.getStuPhone());
        return pst.executeUpdate();

    }

    @Override
    public Stud log(String name, String pwd) throws SQLException {
        String sql = "select * from students where name = ? and password = ?";
        PreparedStatement pst = cont.prepareStatement(sql);
        pst.setString(1,name);
        pst.setString(2,pwd);
        ResultSet  rs = pst.executeQuery();
        if (rs.next()){
            Stud stud = new Stud();
            stud.setStuName(rs.getString("name"));
            stud.setStuPwd(rs.getString("password"));
            stud.setStuPhone(rs.getString("phone"));
            return stud;
        }else
            return null;
    }

    @Override
    public Stud changePwd(String name, String pwd) throws SQLException {
         String sql = "update students set password = ? where name = ?";
          PreparedStatement pst = cont.prepareStatement(sql);
           pst.setString(1,pwd);
            pst.setString(2,name);
             int i = pst.executeUpdate();
             if (i>0){
                 Stud stud = new Stud();
                 stud.setStuName(name);
                 stud.setStuPwd(pwd);
                 return stud;
             }
        return null;
    }

    @Override
    public Stud deleteStu(String name, String pwd) throws SQLException {
        String sql = "delete FROM students WHERE name = ? and password = ? ";
        PreparedStatement state = cont.prepareStatement(sql);
        state.setString(1,name);
        state.setString(2,pwd);
        int i = state.executeUpdate();
        if (i > 0){
            System.out.println("删除成功");
        }else {
            System.out.println("删除失败");
        }
        return null;
    }

    @Override
    public Stud changePho(String name, String phone) throws SQLException {

        return null;
    }


}
